import router from "@/router";
import { useUserStoreHook, usePermissionStoreHook } from "jmash-core";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
NProgress.configure({ showSpinner: false }); // 进度条
const permissionStore = usePermissionStoreHook();
// 白名单路由
const whiteList = ["/login", "/secondLogin"];
router.beforeEach(async (to, from, next) => {
    NProgress.start();
    const userStore = useUserStoreHook();
    const hasToken = userStore.token;
    const tenant = userStore.user.tenant;
    if (hasToken) {
        if (to.path === "/login") {
            // 如果已登录，跳转首页
            next({ path: "/", query: Object.assign(to.query, { tenant: tenant }) });
            NProgress.done();
        }
        else {
            const hasRoles = userStore.user.roleCodes && userStore.user.roleCodes.length > 0;
            if (hasRoles) {
                // 未匹配到任何路由，跳转404
                if (to.matched.length === 0) {
                    from.name
                        ? next({ name: from.name, query: { tenant: tenant } })
                        : next({ path: "/404", query: { tenant: tenant } });
                }
                else if (to.query.tenant) {
                    next();
                }
                else {
                    to.query.tenant = tenant;
                    next({
                        ...to,
                    });
                }
            }
            else {
                try {
                    const rolesPerms = await userStore.getRoleInfo();
                    await userStore.getUserInfo();
                    const accessRoutes = await permissionStore.generateRoutes(rolesPerms);
                    accessRoutes.forEach((route) => {
                        router.addRoute(route);
                    });
                    next({
                        ...to,
                        replace: true,
                        query: Object.assign(to.query, { tenant: tenant }),
                    });
                }
                catch (error) {
                    // 移除 token 并跳转登录页
                    await userStore.resetToken();
                    next({
                        path: `/login?redirect=${to.path}`,
                        query: { tenant: tenant },
                    });
                    NProgress.done();
                }
            }
        }
    }
    else {
        // 未登录可以访问白名单页面
        if (whiteList.indexOf(to.path) !== -1 && to.query.tenant) {
            next();
        }
        else if (whiteList.indexOf(to.path) !== -1) {
            to.query.tenant = tenant;
            next({
                ...to,
                replace: true,
            });
        }
        else {
            next({ path: `/login?redirect=${to.path}`, query: { tenant: tenant } });
            NProgress.done();
        }
    }
});
router.afterEach(() => {
    NProgress.done();
});
